// ===== 数据管理 =====

// 初始化数据
function initData() {
    // 如果本地没有数据，初始化示例数据
    if (!localStorage.getItem('medicines')) {
        const sampleMedicines = [
            { id: 1, name: '布洛芬缓释胶囊', category: '解热镇痛', stock: 15, expiry: '2025-12-31', icon: '💊' },
            { id: 2, name: '复方感冒灵颗粒', category: '感冒用药', stock: 6, expiry: '2024-08-15', icon: '🧪' },
            { id: 3, name: '盐酸左氧氟沙星片', category: '抗生素', stock: 2, expiry: '2025-05-20', icon: '💉' },
            { id: 4, name: '维生素C咀嚼片', category: '保健品', stock: 45, expiry: '2024-05-31', icon: '🍬' },
            { id: 5, name: '盐酸小檗碱片', category: '消化系统', stock: 85, expiry: '2025-08-20', icon: '🩹' },
        ];
        localStorage.setItem('medicines', JSON.stringify(sampleMedicines));
    }

    if (!localStorage.getItem('reminders')) {
        const sampleReminders = [
            { id: 1, medicineId: 1, name: '布洛芬缓释胶囊', time: '08:00', dosage: '每次1粒', completed: true, icon: '💊', color: 'blue' },
            { id: 2, medicineId: 1, name: '布洛芬缓释胶囊', time: '12:00', dosage: '每次1粒', completed: false, icon: '💊', color: 'blue' },
            { id: 3, medicineId: 4, name: '维生素C片', time: '18:00', dosage: '每次2片', completed: false, icon: '🧪', color: 'green' },
            { id: 4, medicineId: 5, name: '盐酸小檗碱片', time: '20:00', dosage: '每次3片', completed: false, icon: '💉', color: 'purple' },
            { id: 5, medicineId: 2, name: '复方感冒灵颗粒', time: '22:00', dosage: '1袋冲服', completed: false, icon: '🧪', color: 'orange' },
        ];
        localStorage.setItem('reminders', JSON.stringify(sampleReminders));
    }

    if (!localStorage.getItem('notifications')) {
        const sampleNotifications = [
            { id: 1, title: '用药提醒', content: '该服用布洛芬缓释胶囊了', time: '10分钟前', read: false, icon: '💊', color: 'blue' },
            { id: 2, title: '过期提醒', content: '维生素C咀嚼片将在1个月内过期', time: '1小时前', read: false, icon: '⚠️', color: 'orange' },
            { id: 3, title: '库存提醒', content: '盐酸左氧氟沙星片库存不足', time: '2小时前', read: false, icon: '📦', color: 'red' },
        ];
        localStorage.setItem('notifications', JSON.stringify(sampleNotifications));
    }
}

// 获取数据
function getMedicines() {
    return JSON.parse(localStorage.getItem('medicines') || '[]');
}

function getReminders() {
    return JSON.parse(localStorage.getItem('reminders') || '[]');
}

function getNotifications() {
    return JSON.parse(localStorage.getItem('notifications') || '[]');
}

// 保存数据
function saveReminders(reminders) {
    localStorage.setItem('reminders', JSON.stringify(reminders));
}

function saveNotifications(notifications) {
    localStorage.setItem('notifications', JSON.stringify(notifications));
}

// ===== 页面初始化 =====

document.addEventListener('DOMContentLoaded', () => {
    initData();
    updateGreeting();
    updateStatistics();
    loadReminders();
    loadNotifications();
    startAutoRefresh();
    initHealthTips();
});

// ===== 问候语更新 =====

function updateGreeting() {
    const hour = new Date().getHours();
    const days = ['日', '一', '二', '三', '四', '五', '六'];
    const now = new Date();
    const dateStr = `${now.getMonth() + 1}月${now.getDate()}日 星期${days[now.getDay()]}`;

    let greeting = '';
    if (hour < 6) greeting = '凌晨好';
    else if (hour < 9) greeting = '早上好';
    else if (hour < 12) greeting = '上午好';
    else if (hour < 14) greeting = '中午好';
    else if (hour < 18) greeting = '下午好';
    else if (hour < 22) greeting = '晚上好';
    else greeting = '夜深了';

    document.getElementById('greetingText').textContent = `${greeting}，王先生 · ${dateStr}`;
}

// ===== 统计数据更新 =====

function updateStatistics() {
    const medicines = getMedicines();
    const reminders = getReminders();

    // 总药品数
    const totalMedicines = medicines.length;
    document.getElementById('totalMedicines').textContent = totalMedicines;
    updateProgressRing('totalMedicineProgress', totalMedicines / 30); // 假设最大30种

    // 即将过期（30天内）
    const today = new Date();
    const expiringCount = medicines.filter(med => {
        const expiryDate = new Date(med.expiry);
        const daysUntilExpiry = (expiryDate - today) / (1000 * 60 * 60 * 24);
        return daysUntilExpiry > 0 && daysUntilExpiry <= 30;
    }).length;
    document.getElementById('expiringCount').textContent = expiringCount;
    updateProgressRing('expiringProgress', expiringCount / 10); // 假设最大10个

    // 待服用
    const pendingCount = reminders.filter(r => !r.completed).length;
    document.getElementById('pendingCount').textContent = pendingCount;
    updateProgressRing('pendingProgress', pendingCount / 10); // 假设最大10个

    // 服药率
    const completedCount = reminders.filter(r => r.completed).length;
    const complianceRate = reminders.length > 0 ? Math.round((completedCount / reminders.length) * 100) : 0;
    document.getElementById('complianceRate').textContent = `${complianceRate}%`;
    updateProgressRing('complianceProgress', complianceRate / 100);
}

function updateProgressRing(id, progress) {
    const circumference = 2 * Math.PI * 16;
    const offset = circumference * (1 - Math.min(progress, 1));

    setTimeout(() => {
        const ring = document.getElementById(id);
        if (ring) {
            ring.style.strokeDashoffset = offset;
        }
    }, 100);
}

// ===== 提醒列表 =====

function loadReminders() {
    const reminders = getReminders();
    const reminderList = document.getElementById('reminderList');
    const completedCount = reminders.filter(r => r.completed).length;
    const totalCount = reminders.length;

    // 更新统计
    document.getElementById('completedReminders').textContent = completedCount;
    document.getElementById('totalReminders').textContent = totalCount;

    // 更新进度条
    const progress = totalCount > 0 ? (completedCount / totalCount) * 100 : 0;
    document.getElementById('reminderProgress').style.width = `${progress}%`;

    // 只显示前3个未完成的提醒
    const pendingReminders = reminders.filter(r => !r.completed).slice(0, 3);

    if (pendingReminders.length === 0) {
        reminderList.innerHTML = `
            <div class="text-center py-8">
                <div class="text-4xl mb-2">🎉</div>
                <div class="text-sm text-gray-500">今天的提醒都已完成！</div>
            </div>
        `;
        return;
    }

    reminderList.innerHTML = pendingReminders.map((reminder, index) => {
        const colors = {
            blue: 'from-blue-50 to-purple-50',
            green: 'from-green-50 to-emerald-50',
            purple: 'from-purple-50 to-pink-50',
            orange: 'from-orange-50 to-amber-50'
        };

        return `
            <div class="flex items-center gap-3 p-3 bg-gradient-to-r ${colors[reminder.color]} rounded-2xl fade-in" style="animation-delay: ${index * 0.1}s">
                <div class="w-12 h-12 bg-white rounded-xl flex items-center justify-center shadow-sm">
                    <span class="text-2xl">${reminder.icon}</span>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="font-semibold text-gray-900 text-sm">${reminder.name}</div>
                    <div class="text-xs text-gray-500">${reminder.time} · ${reminder.dosage}</div>
                </div>
                <button onclick="markReminderComplete(${reminder.id})" 
                    class="px-4 py-2 bg-black text-white rounded-xl text-xs font-medium hover:bg-gray-800 transition-all hover:scale-105">
                    标记
                </button>
            </div>
        `;
    }).join('');
}

function markReminderComplete(id) {
    const reminders = getReminders();
    const index = reminders.findIndex(r => r.id === id);

    if (index !== -1) {
        reminders[index].completed = true;
        saveReminders(reminders);

        // 显示成功提示
        showToast('✅ 已标记完成', 'success');

        // 刷新显示
        loadReminders();
        updateStatistics();

        // 添加完成动画
        const reminderElement = event.target.closest('.flex');
        reminderElement.style.transition = 'all 0.3s';
        reminderElement.style.opacity = '0';
        reminderElement.style.transform = 'translateX(20px)';

        setTimeout(() => {
            loadReminders();
        }, 300);
    }
}

// ===== 通知中心 =====

function loadNotifications() {
    const notifications = getNotifications();
    const unreadCount = notifications.filter(n => !n.read).length;

    // 更新徽章
    const badge = document.getElementById('notificationBadge');
    if (unreadCount > 0) {
        badge.textContent = unreadCount;
        badge.style.display = 'flex';
    } else {
        badge.style.display = 'none';
    }

    // 加载通知列表
    const notificationList = document.getElementById('notificationList');

    if (notifications.length === 0) {
        notificationList.innerHTML = `
            <div class="text-center py-16">
                <div class="text-4xl mb-2">🔔</div>
                <div class="text-sm text-gray-500">暂无通知</div>
            </div>
        `;
        return;
    }

    notificationList.innerHTML = notifications.map(notification => {
        const bgColors = {
            blue: 'from-blue-50 to-indigo-50',
            orange: 'from-orange-50 to-amber-50',
            red: 'from-red-50 to-rose-50',
            green: 'from-green-50 to-emerald-50'
        };

        return `
            <div class="p-4 bg-gradient-to-r ${bgColors[notification.color]} rounded-2xl ${notification.read ? 'opacity-60' : ''} cursor-pointer hover:shadow-md transition-all"
                onclick="markNotificationRead(${notification.id})">
                <div class="flex items-start gap-3">
                    <div class="w-10 h-10 bg-white rounded-xl flex items-center justify-center shadow-sm">
                        <span class="text-xl">${notification.icon}</span>
                    </div>
                    <div class="flex-1">
                        <div class="font-semibold text-gray-900 text-sm mb-1">${notification.title}</div>
                        <div class="text-xs text-gray-600 mb-2">${notification.content}</div>
                        <div class="text-xs text-gray-400">${notification.time}</div>
                    </div>
                    ${!notification.read ? '<div class="w-2 h-2 bg-red-500 rounded-full"></div>' : ''}
                </div>
            </div>
        `;
    }).join('');
}

function markNotificationRead(id) {
    const notifications = getNotifications();
    const index = notifications.findIndex(n => n.id === id);

    if (index !== -1 && !notifications[index].read) {
        notifications[index].read = true;
        saveNotifications(notifications);
        loadNotifications();
    }
}

// ===== 健康小贴士 =====

const healthTips = [
    {
        content: '根据您的用药记录，建议定期补充维生素D，有助于提高钙质吸收和免疫力。保持规律的作息，定时服药哦！💪',
        emoji: '🐻'
    },
    {
        content: '服药前请仔细阅读说明书，注意药物的禁忌症和不良反应。如有不适，请及时咨询医生。记得多喝水哦！💧',
        emoji: '🐰'
    },
    {
        content: '药品应存放在阴凉干燥处，避免阳光直射。定期检查药品有效期，过期药品及时清理。让我们一起守护健康！🌟',
        emoji: '🐱'
    }
];

let currentTipIndex = 0;

function initHealthTips() {
    // 随机选择一个小贴士
    currentTipIndex = Math.floor(Math.random() * healthTips.length);
    displayHealthTip();
}

function displayHealthTip() {
    const tip = healthTips[currentTipIndex];
    document.getElementById('healthTipContent').textContent = tip.content;

    // 更新指示器
    const indicators = document.querySelectorAll('#healthTipsCard .flex.gap-1 span');
    indicators.forEach((indicator, index) => {
        if (index === currentTipIndex) {
            indicator.className = 'w-2 h-2 bg-purple-400 rounded-full';
        } else {
            indicator.className = 'w-2 h-2 bg-gray-300 rounded-full';
        }
    });

    // 更新emoji
    const emojiElement = document.querySelector('#healthTipsCard .float-animation');
    emojiElement.textContent = tip.emoji;
}

function nextHealthTip() {
    currentTipIndex = (currentTipIndex + 1) % healthTips.length;
    displayHealthTip();
}

// ===== 搜索功能 =====

document.getElementById('searchBtn')?.addEventListener('click', () => {
    document.getElementById('searchModal').classList.add('active');
    document.getElementById('searchInput').focus();
});

function closeSearchModal() {
    document.getElementById('searchModal').classList.remove('active');
    document.getElementById('searchInput').value = '';
    document.getElementById('searchResults').innerHTML = '';
}

document.getElementById('searchInput')?.addEventListener('input', (e) => {
    const keyword = e.target.value.toLowerCase().trim();
    const medicines = getMedicines();

    if (!keyword) {
        document.getElementById('searchResults').innerHTML = '';
        return;
    }

    const results = medicines.filter(med =>
        med.name.toLowerCase().includes(keyword) ||
        med.category.toLowerCase().includes(keyword)
    );

    const resultsHtml = results.length > 0
        ? results.map(med => `
            <div class="p-3 bg-gray-50 rounded-xl hover:bg-gray-100 cursor-pointer transition-colors"
                onclick="navigateTo('medicine_detail.html?id=${med.id}')">
                <div class="flex items-center gap-3">
                    <span class="text-2xl">${med.icon}</span>
                    <div class="flex-1">
                        <div class="font-semibold text-gray-900 text-sm">${med.name}</div>
                        <div class="text-xs text-gray-500">${med.category} · 库存: ${med.stock}</div>
                    </div>
                </div>
            </div>
        `).join('')
        : '<div class="text-center py-8 text-sm text-gray-500">未找到相关药品</div>';

    document.getElementById('searchResults').innerHTML = resultsHtml;
});

// ===== 通知弹窗 =====

document.getElementById('notificationBtn')?.addEventListener('click', () => {
    document.getElementById('notificationModal').classList.add('active');
    loadNotifications();
});

function closeNotificationModal() {
    document.getElementById('notificationModal').classList.remove('active');
}

// ===== 统计卡片点击事件 =====

function showExpiringMedicines() {
    const medicines = getMedicines();
    const today = new Date();
    const expiringMeds = medicines.filter(med => {
        const expiryDate = new Date(med.expiry);
        const daysUntilExpiry = (expiryDate - today) / (1000 * 60 * 60 * 24);
        return daysUntilExpiry > 0 && daysUntilExpiry <= 30;
    });

    if (expiringMeds.length === 0) {
        showToast('✅ 暂无即将过期的药品', 'success');
    } else {
        const message = expiringMeds.map(m => m.name).join('、');
        showToast(`⚠️ ${message} 即将过期`, 'warning');
    }
}

function showComplianceDetails() {
    const reminders = getReminders();
    const completedCount = reminders.filter(r => r.completed).length;
    const rate = reminders.length > 0 ? Math.round((completedCount / reminders.length) * 100) : 0;

    let message = '';
    if (rate >= 90) message = `🎉 太棒了！您的服药率达到${rate}%，继续保持！`;
    else if (rate >= 70) message = `👍 不错！您的服药率为${rate}%，再接再厉！`;
    else message = `💪 您的服药率为${rate}%，让我们一起努力按时服药吧！`;

    showToast(message, 'info');
}

// ===== 工具函数 =====

function navigateTo(url) {
    window.location.href = url;
}

function showToast(message, type = 'info') {
    const colors = {
        success: 'from-green-500 to-emerald-500',
        warning: 'from-orange-500 to-amber-500',
        error: 'from-red-500 to-rose-500',
        info: 'from-blue-500 to-indigo-500'
    };

    const toast = document.createElement('div');
    toast.className = 'fixed top-20 left-1/2 transform -translate-x-1/2 z-50 fade-in';
    toast.innerHTML = `
        <div class="glass-card px-6 py-3 rounded-2xl shadow-2xl bg-gradient-to-r ${colors[type]} text-white font-semibold">
            ${message}
        </div>
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translate(-50%, -20px)';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// ===== 自动刷新 =====

function startAutoRefresh() {
    // 每分钟更新一次问候语和时间
    setInterval(updateGreeting, 60000);

    // 每5分钟检查一次提醒
    setInterval(() => {
        loadReminders();
        updateStatistics();
    }, 300000);
}

// ===== 点击外部关闭弹窗 =====

document.getElementById('searchModal')?.addEventListener('click', (e) => {
    if (e.target.id === 'searchModal') {
        closeSearchModal();
    }
});

document.getElementById('notificationModal')?.addEventListener('click', (e) => {
    if (e.target.id === 'notificationModal') {
        closeNotificationModal();
    }
});

// ===== 键盘快捷键 =====

document.addEventListener('keydown', (e) => {
    // ESC 关闭弹窗
    if (e.key === 'Escape') {
        closeSearchModal();
        closeNotificationModal();
    }

    // Ctrl/Cmd + K 打开搜索
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('searchBtn').click();
    }
});

